package com.zp.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zp.dao.UserDao;
import com.zp.dao.impl.UserDaoImpl;
import com.zp.domain.User;
import com.zp.utils.Base64Util;
import com.zp.utils.CommonUtil;
import com.zp.utils.MD5Util;
import com.zp.utils.ResultUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/update")
public class UpdateUserServlet extends HttpServlet {

    private PrintWriter out;
    private UserDao userDao;

    @Override
    public void init() throws ServletException {
        userDao = new UserDaoImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        out = response.getWriter();
        Gson gson = new Gson();
        User user = new User();

        int row = 0;
        String password = null;
        try {
            String json = CommonUtil.readJSONData(request.getReader());
            user = gson.fromJson(json, User.class);
            String plainText = user.getPassword();
            // 密码加密
            password = Base64Util.getEncodeBase64(MD5Util.getMD5(plainText));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        try {
            user.setPassword(password);
            row = userDao.updateUserBySno(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (row == 1) {
            out.print(gson.toJson(ResultUtil.success()));
        } else {
            out.print(gson.toJson(ResultUtil.error("更新用户失败")));
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }


}

